/*
 * JSON001Status.java
 *
 * Created on 9 październik 2007, 23:16
 *
 */

package kosciak.blip4j.api.json001;


import kosciak.blip4j.Picture;
import kosciak.blip4j.Status;
import kosciak.blip4j.Transport;
import kosciak.blip4j.User;

import java.net.MalformedURLException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Implementation of Status for Blip.pl API version 0.01 using JSON
 * @author Wojtek 'KosciaK' Pietrzok
 * @since 0.1
 */
class JSON001Status extends Status {
    
    /**
     * Creates a new instance of JSON001Status
     */
    private JSON001Status(int id, 
                         String body, 
                         Date date, 
                         User from, 
                         Transport transport,
                         List<Picture> pictures) {
        
        super(id, body, date, from, transport, pictures);
    }
    
    static Status getInstance(JSONObject obj) throws JSONException {
        User from = JSON001User.getInstance(obj.getJSONObject("src_user"));
        return getInstance(obj, from);
    }

    static Status getInstance(JSONObject obj, User from) throws JSONException {
        int id = obj.getInt("id");
        String body = obj.getString("body");
        Date date = new Date(obj.getLong("created_at_epoch")*1000);
        Transport transport = JSON001Transport.getInstance(obj.getJSONObject("transport"));
        List<Picture> pictures = new ArrayList<Picture>();
        JSONArray picturesArray = obj.getJSONArray("attached_pictures");
        for (int i = 0 ; i < picturesArray.length() ; i++) {
            Picture picture = null;
            try {
                picture = JSON001Picture.getInstance(picturesArray.getJSONObject(i));
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
                continue;
            }
            pictures.add(picture);
        }
        return new JSON001Status(id, body, date, from, transport, pictures);
    }   
}
